package com.syj.collect.model;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.syj.collect.Present.ProjectDetailPresent;
import com.syj.collect.adapter.AdapterWaterAnalyze;
import com.syj.collect.adapter.MyPicAdapter;
import com.syj.collect.adapter.TagAdapter;
import com.syj.collect.app.R;
import com.syj.collect.base.BaseMvpAvtivity;
import com.syj.collect.entry.DetailBean;
import com.syj.collect.entry.KeyvalueBean;
import com.syj.collect.entry.MyCollectBean;
import com.syj.collect.entry.TagAdapterData;
import com.syj.collect.entry.UpdataHead;
import com.syj.collect.entry.WaterColorBean;
import com.syj.collect.listnner.MyItemListener;
import com.syj.collect.utils.Glide4Engine;
import com.syj.collect.utils.GsonUtil;
import com.syj.collect.utils.LogUtils;
import com.syj.collect.utils.ToastMgr;
import com.syj.collect.view.ProjectDetailView;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

//model 算是一个Activiy
public class ProjectDetailActivity extends BaseMvpAvtivity<ProjectDetailView, ProjectDetailPresent> implements ProjectDetailView {

    private MyCollectBean.DataDTO.ListDTO data;
    private EditText fixmsg;
    private TextView colorBlock;
    private EditText addmsg;
    private Spinner spinner;
    private AdapterWaterAnalyze adapterWaterAnalyze;
    private MyPicAdapter picAdapter;
    private TagAdapter tagAnalyze;
    //底部已经提交模块
    private ImageView tv_subtype;
    private LinearLayout ll_subtyoe;
    //头部审核一件
    private LinearLayout ll_etll;
    private TextView et_view;
    private View view;
    private String staCode;

    private TextView msave;
    private TextView f_submit;

    private TextView wat;
    private RecyclerView analyrec;
    private int picpos;
    private RxPermissions rxPermissions;
    private List<Uri> mSelected;
    private List<DetailBean.DataDTO.ImgMapDTO> oldImgList;
    private String id;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prodetail);
        initTitle("项目详情");
        rxPermissions = new RxPermissions(this);
        Bundle bu = getIntent().getBundleExtra("bundle");


        RecyclerView picrec = (RecyclerView) findViewById(R.id.com_rec);
        fixmsg = (EditText) findViewById(R.id.fixmsg);
        colorBlock = (TextView) findViewById(R.id.colorblock);
        colorBlock.setVisibility(View.GONE);
        wat = (TextView) findViewById(R.id.wat);
        wat.setVisibility(View.VISIBLE);
        msave = (TextView) findViewById(R.id.msave);
        f_submit = (TextView) findViewById(R.id.f_submit);
        f_submit.setOnClickListener(this);
        addmsg = (EditText) findViewById(R.id.supplymsg);
        spinner = (Spinner) findViewById(R.id.mspinner);
        view = findViewById(R.id.view);


        tv_subtype = findViewById(R.id.tv_subtype);
        ll_subtyoe = findViewById(R.id.ll_subtyoe);
        ll_etll = findViewById(R.id.ll_etll);
        et_view = findViewById(R.id.et_view);

        picrec.setLayoutManager(new GridLayoutManager(this, 3));
        picAdapter = new MyPicAdapter();
        picrec.setAdapter(picAdapter);
        picAdapter.setonClick(new MyItemListener() {
            @Override
            public void onmListenner(int pos) {
                picpos = pos;
                rxPermissions.requestEachCombined(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Observer<Permission>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(Permission permission) {
                                if (permission.granted) {
                                    //成功获取权限
                                    Matisse.from(ProjectDetailActivity.this)
                                            .choose(MimeType.ofImage())
                                            .capture(true)
                                            .countable(true)
                                            .captureStrategy(new CaptureStrategy(true, "com.syj.collect.app"))
                                            .maxSelectable(1)
                                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                            .thumbnailScale(0.85f)
                                            .imageEngine(new Glide4Engine())//Glide4
                                            .forResult(1);

                                } else if (permission.shouldShowRequestPermissionRationale) {
                                    //用户拒绝权限
                                    ToastMgr.builder.display("您禁止了拍照权限");
                                } else {
                                    //用户禁止权限勾选了不在提示
                                    Intent localIntent = new Intent();
                                    localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                    localIntent.setData(Uri.fromParts("package", ProjectDetailActivity.this.getPackageName(), null));
                                    startActivity(localIntent);
                                    LogUtils.i("用户禁止权限勾选了不在提示");
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            }
        });


        analyrec = (RecyclerView) findViewById(R.id.com_rec1);
//        adapterWaterAnalyze = new AdapterWaterAnalyze(1);
//        analyrec.setAdapter(adapterWaterAnalyze);
        analyrec.setLayoutManager(new GridLayoutManager(this, 5));


        RecyclerView tagRec = (RecyclerView) findViewById(R.id.com_rec2);
        tagAnalyze = new TagAdapter();
        FlexboxLayoutManager fLayout = new FlexboxLayoutManager(this);
        fLayout.setFlexWrap(FlexWrap.WRAP);
        fLayout.setFlexDirection(FlexDirection.ROW);
        fLayout.setAlignItems(AlignItems.STRETCH);
        fLayout.setJustifyContent(JustifyContent.FLEX_START);
        tagRec.setLayoutManager(fLayout);
        tagRec.setAdapter(tagAnalyze);
        //tagAnalyze.upDate(null);

        if (bu != null) /*data = (MyCollectBean.DataDTO.ListDTO)*/ {
            id = bu.getString("id");
            presenter.getDetailData(id);
        }

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (R.id.f_submit == view.getId()) {

            presenter.upLoadFiles(false, id, staCode, picAdapter.getPicList(), oldImgList, adapterWaterAnalyze.getDate(), fixmsg.getText().toString(), addmsg.getText().toString(), wat.getText().toString());

           /* for (int i = 0; i < picAdapter.getPicList().size(); i++) {
                Log.e("picstr", picAdapter.getPicList().get(i));
            }*/
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        if (requestCode == 1 && resultCode == RESULT_OK) {
//            List mSelected = Matisse.obtainResult(data);
//            Log.e("results", requestCode + mSelected.get(0).toString());
//            picAdapter.upDate(this, mSelected);
//        }


        if (requestCode == 1 && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainResult(data);
            //loadingDialog.show();
            // String realPathFromUri = getRealPathFromUri(this, Uri.parse(mSelected.get(0).toString()));
            //presenter.upLoadFile(getRealFilePath(this, Uri.parse(mSelected.get(0).toString())));
            picAdapter.upDate(picpos, getRealFilePath(this, Uri.parse(mSelected.get(0).toString())));
        }
    }

    /**
     * 根据Uri获取文件真实地址
     */
    public static String getRealFilePath(Context context, Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String realPath = null;
        if (scheme == null)
            realPath = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            realPath = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA},
                    null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        realPath = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        if (TextUtils.isEmpty(realPath)) {
            if (uri != null) {
                String uriString = uri.toString();
                int index = uriString.lastIndexOf("/");
                String imageName = uriString.substring(index);
                File storageDir;

                storageDir = Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES);
                File file = new File(storageDir, imageName);
                if (file.exists()) {
                    realPath = file.getAbsolutePath();
                } else {
                    storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                    File file1 = new File(storageDir, imageName);
                    realPath = file1.getAbsolutePath();
                }
            }
        }
        return realPath;
    }


    private void initSpinner(List<WaterColorBean.WaterColor> list) {
        ArrayAdapter<WaterColorBean.WaterColor> adapter = new ArrayAdapter<WaterColorBean.WaterColor>(this, android.R.layout.simple_spinner_item, list);
        //第三步：设置下拉列表下拉时的菜单样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //第四步：将适配器添加到下拉列表上
        spinner.setAdapter(adapter);
        //第五步：添加监听器，为下拉列表设置事件的响应
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                colorBlock.setBackgroundColor(Color.parseColor(list.get(position).getDescription()));

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    @Override
    public ProjectDetailPresent initPresenter() {
        return new ProjectDetailPresent();
    }

    public static void StartAction(Context context, String id) {
        Intent intent = new Intent();
        intent.setClass(context, ProjectDetailActivity.class);
        Bundle bu = new Bundle();
        bu.putString("id", id + "");
//        bu.putString("typeid", typeid + "");
        intent.putExtra("bundle", bu);
        context.startActivity(intent);

    }

    @Override
    public void initSuccess(String str) {
        Toast.makeText(this, str, Toast.LENGTH_LONG).show();

    }

    @Override
    public void initFail(String str) {
        Toast.makeText(this, str, Toast.LENGTH_LONG).show();
    }

    private List<TagAdapterData.WaterBean> tagl;
    private DetailBean.DataDTO bean;

    @Override
    public void initSuccess(DetailBean.DataDTO data) {
        bean = data;
        staCode = bean.getStationCode();
        oldImgList = bean.getImgMap();
        if (!data.getPollutionStatus().isEmpty()) {
            String pollutionStatus = data.getPollutionStatus();
            String[] split = pollutionStatus.split(";");
            tagl = new ArrayList<>();
            for (int i = 0; i < split.length; i++) {
                TagAdapterData.WaterBean bean = new TagAdapterData.WaterBean();
                bean.setLabel(split[i]);
                bean.setIscheckd(true);
                tagl.add(bean);

            }
            tagAnalyze.upDate(tagl);
        }

        if (data.getIsSubmit().equals("1") && data.getAuditStatus().equals("0")) {
            ll_subtyoe.setVisibility(View.VISIBLE);
            adapterWaterAnalyze = new AdapterWaterAnalyze(1);
            picAdapter.setonClick(null);

        } else if (data.getIsSubmit().equals("1") && data.getAuditStatus().equals("3")) {
            //审核未通过
            ll_etll.setVisibility(View.VISIBLE);
            view.setVisibility(View.VISIBLE);

            msave.setVisibility(View.GONE);
            f_submit.setVisibility(View.VISIBLE);
            adapterWaterAnalyze = new AdapterWaterAnalyze(0);
        } else if (data.getAuditStatus().equals("0") && data.getIsSubmit().equals("0")) {
            ll_etll.setVisibility(View.GONE);
            view.setVisibility(View.VISIBLE);

            msave.setVisibility(View.GONE);
            f_submit.setVisibility(View.VISIBLE);
            adapterWaterAnalyze = new AdapterWaterAnalyze(0);
        }

        analyrec.setAdapter(adapterWaterAnalyze);
        //
        List<KeyvalueBean> oo = new ArrayList<>();
        oo.add(new KeyvalueBean("cod", data.getCod()));
        oo.add(new KeyvalueBean("o2", data.getAnionic()));
        oo.add(new KeyvalueBean("tp", data.getTp()));
        oo.add(new KeyvalueBean("tn", data.getTn()));
        oo.add(new KeyvalueBean("nh3", data.getNh3()));
        adapterWaterAnalyze.upData(oo);
        fixmsg.setText(!isEmpty(data.getDescription())?data.getDescription():"");//固定信息

        if (data.getUrls() != null) {

            picAdapter.upDate(data.getUrls());
        }
        spinner.setVisibility(View.GONE);
        String[] temp = data.getRemarks().split(";");
        try {

            if (temp.length > 1) {
                if (temp[1].contains("#")) {
                    colorBlock.setVisibility(View.VISIBLE);
                    GradientDrawable myGrad = (GradientDrawable) colorBlock.getBackground();
                    myGrad.setColor(Color.parseColor((temp[1])));

                    wat.setText(temp[0] + "");
                } else if (temp[0].contains("#")) {
                    wat.setText(temp[1] + "");
                    colorBlock.setVisibility(View.VISIBLE);
                    GradientDrawable myGrad = (GradientDrawable) colorBlock.getBackground();
                    myGrad.setColor(Color.parseColor((temp[0])));
                }
            } else {

                wat.setText(temp[0] + "");
            }


        } catch (Exception e) {
            colorBlock.setVisibility(View.GONE);
            wat.setText(data.getRemarks());
        }
        et_view.setText("未通过原因:" + data.getAuditMsg() + "");

        addmsg.setText(data.getAddMsg() + "");
    }

    @Override
    public void initPicSuccess(String str) {
        UpdataHead updataHead = GsonUtil.gsonToBean(str, UpdataHead.class);
        updataHead.getData().getFilePath();
    }

    @Override
    public void initPicFail(String str) {
        ToastMgr.builder.display("图片上传失败，请稍后在试");
    }
    public boolean isEmpty(String str) {
        if (str != "" && str != null && !str.isEmpty()) {
            return false;
        } else return true;

    }
}
